package com.qitmiaojie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qitmiaojie.controller.utils.Result;
import com.qitmiaojie.mapper.NoticeMapper;
import com.qitmiaojie.mapper.QuestionMapper;
import com.qitmiaojie.mapper.TemperatureMapper;
import com.qitmiaojie.mapper.UserMapper;
import com.qitmiaojie.pojo.Notice;
import com.qitmiaojie.pojo.Question;

import com.qitmiaojie.pojo.Temperature;
import com.qitmiaojie.pojo.dto.QuestionDto;
import com.qitmiaojie.pojo.dto.QuestionPageResp;
import com.qitmiaojie.service.ActivityService;
import com.qitmiaojie.service.NoticeService;
import com.qitmiaojie.service.QuestionService;
import com.qitmiaojie.test.LexicalAnalysis;
import com.qitmiaojie.test.TBProcess;
import com.tencentcloudapi.nlp.v20190408.models.*;
import com.tencentcloudapi.tbp.v20190627.models.Group;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
/***
* @description 聊天机器人1.0
* @author miaojie
* @date  2023/3/11
*/
@Slf4j
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private TemperatureMapper temperatureMapper;

    @Override
    public Result getAnswer(String question) {
        Integer id = userMapper.selectByUsername(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).getId();
        String chatBotMessage = TBProcess.getChatBotMessage(id.toString(), question);
        log.info(chatBotMessage);
        if (chatBotMessage != null){
            return Result.success(chatBotMessage);
        }
        List<String> keywords = extractKeywords(question);
        // 根据关键词从数据库中获取匹配度最高的答案
        Map<String,Integer> map = new HashMap<>();
        List<Question> list = list();
        Optional<Question> max = list.stream().filter(question1 -> {
            int count = 0;
            String keywords1 = question1.getKeywords();
            String[] split = keywords1.split(",");

            for (String s : split) {
                log.info("切割的" + s);
                boolean contains = keywords.contains(s);
                if (contains) {
                    log.info(s);
                    map.merge(question1.getId(), 1, Integer::sum);
                }
                System.out.println(split);
            }
            return map.get(question1.getId()) != null;
        }).max(Comparator.comparingInt(question2 -> map.get(question2.getId())));
//        log.info(String.valueOf(max.isEmpty()));
//        log.info(String.valueOf(max.isPresent()));
       // log.info("max = " + max.get().getAnswer());
        log.info(max.toString());
        return Result.success(max == null ? "抱歉，我听不懂您的问题" : max.get().getAnswer());
    }



    /*public static void main(String[] args) {
        String str = "发布公告 标题为 1234 内容为 123 ";
        System.out.println();
        System.out.println(str.substring(str.indexOf("标题为")+3 , str.lastIndexOf("内容为")));
        String str23 = "miaojie";
        String str2 = "苗杰";
        System.out.println(str.toLowerCase());
        System.out.println(str.toUpperCase());
        System.out.println(str2.toLowerCase());
    }*/
    @Override
    public Result addQuestion(QuestionDto questionDto) {
        List<String> list = extractKeywords(questionDto.getQuestion());
        Question question = new Question();
        question.setQuestion(questionDto.getQuestion());
        question.setAnswer(questionDto.getAnswer());
        StringBuilder keywords= new StringBuilder();
        for (int i = 0; i < list.size()-1; i++) {
            keywords.append(list.get(i)).append(",");
//            String lower = keywords.toLowerCase();
        }
        keywords.append(list.get(list.size() - 1));
        question.setKeywords(keywords.toString());
        save(question);
        return Result.success("添加成功",null);
    }

    @Override
    public Result getAnswer2(String question) {
        Result result = handlerSendNotice(question);
        if (result != null){
            return result;
        }
        List<String> keywords = extractKeywords(question);
        // 根据关键词从数据库中获取匹配度最高的答案
        Map<String,Integer> map = new HashMap<>();
        List<Question> list = list();
        Optional<Question> max = list.stream().filter(question1 -> {
            int count = 0;
            String keywords1 = question1.getKeywords();
            String[] split = keywords1.split(",");

            for (String s : split) {
                log.info("切割的" + s);
                boolean contains = keywords.contains(s);
                if (contains) {
                    log.info(s);
                    map.merge(question1.getId(), 1, Integer::sum);
                }
                System.out.println(Arrays.toString(split));
            }
            return map.get(question1.getId()) != null;
        }).max(Comparator.comparingInt(question2 -> map.get(question2.getId())));
//        log.info(String.valueOf(max.isEmpty()));
//        log.info(String.valueOf(max.isPresent()));
        // log.info("max = " + max.get().getAnswer());
        log.info(max.toString());
        return Result.success(max == null || max.toString().equals("Optional.empty") ? "抱歉，我听不懂您的问题" : max.get().getAnswer());
    }

    @Override
    public Result startRenwu(String id, String question) {
        if ("1".equals(id)){
            //进入任务模式
            log.info("进入任务模式...");
            if (question.contains("上报体温")){
                String[] split = question.split(",");
                log.info("temp + " + split[1] + split[2]+ split[3]);
                Temperature temperature = new Temperature();
                temperature.setDay(new Date());
                log.info("setday ....");
                Integer uid = userMapper.selectByUsername(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString()).getId();
                temperature.setUserid(uid);
                log.info("uid = " + uid);
                temperature.setMorning(split[1]);
                temperature.setNoon(split[2]);
                temperature.setNight(split[3]);
                log.info("temp pojo = " + temperature.toString());
                if (Double.parseDouble(split[1]) > 37.5
                        &&Double.parseDouble(split[2]) > 37.5  || Double.parseDouble(split[2]) > 37.5 &&Double.parseDouble(split[3]) > 37.5 ||Double.parseDouble(split[1]) > 37.5 &&Double.parseDouble(split[3]) > 37.5 ) {
                    temperature.setStatus("异常");
                }else {
                    temperature.setStatus("正常");
                }
                temperatureMapper.insert(temperature);
                log.info("插入成功！");
            }
        }
        return Result.success("已收到您的任务请求，请稍后查看任务状态是否完成。");
    }

    @Override
    public Result list(Integer currentPage, Integer pageSize) {

        IPage<Question> iPage = new Page<>(currentPage,pageSize);
        page(iPage);
        QuestionPageResp pageResp = new QuestionPageResp();
        pageResp.setRows(iPage.getRecords());
        pageResp.setTotal(iPage.getTotal());
        pageResp.setCurrentPage(iPage.getCurrent());
        pageResp.setCurrentPage(iPage.getPages());
        return Result.success(pageResp);
    }

    @Override
    public Result deleteById(String id) {
        removeById(id);
        return Result.success("删除成功",null);
    }

    private Result handlerSendNotice(String question) {
        if (question.contains("发布公告")||question.contains("发布一个公告")
                && question.contains("标题为")  && question.contains("内容为")){
            publishNotice(question).thenAccept(result -> {
                // 公告发布完成，可以在这里进行一些操作，例如记录日志或发送通知等
                log.info("异步发布公告完成！");
            });
            return Result.success("已收到您的公告请求，请稍后查看公告发布状态。");
        }
        return null;
    }

    private List<String> extractKeywords(String question) {
        List<String> keywords = new ArrayList<>();
        LexicalAnalysisResponse lars = LexicalAnalysis.lexicalAnalysisResponse(question);

        for (PosToken nt : lars.getPosTokens()) {
            try {
                if (nt.getPos().startsWith("n") ||nt.getPos().startsWith("g")) { // 过滤掉非名词/学术词汇词性的单词
                    keywords.add(nt.getWord());
                }else if (nt.getPos().startsWith("a")){
                    keywords.add(nt.getWord());
                }else {
                    keywords.add(nt.getWord());
                }
            } catch (Exception e) {
                throw new RuntimeException("添加失败！");
            }
        }
        log.info(keywords.toString());

        return keywords;
    }

    public CompletableFuture<Void> publishNotice(String question) {
        return CompletableFuture.runAsync(() -> {
            String title = question.substring(question.indexOf("标题为")+3 , question.lastIndexOf("内容为"));
            String content = question.substring(question.indexOf("内容为")+3 );
            Notice notice = new Notice();
            notice.setContent(content);
            notice.setDatetime(LocalDateTime.now());
            notice.setTitle(title);
            noticeMapper.insert(notice);
        });
    }






}
